package com.clgk.wechatmall.partner.service.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.clgk.wechatmall.common.ThreadLocals;
import com.clgk.wechatmall.common.sql.Page;
import com.clgk.wechatmall.manager.dao.ManagerDao;
import com.clgk.wechatmall.manager.entity.ManagerVo;
import com.clgk.wechatmall.partner.bean.CityBean;
import com.clgk.wechatmall.partner.bean.PartnerBean;
import com.clgk.wechatmall.partner.dao.PartnerDao;
import com.clgk.wechatmall.partner.service.PartnerService;

@Service
@Transactional
public class PartnerServiceImpl implements PartnerService {

	@Resource PartnerDao partnerDao;
	@Resource ManagerDao managerDao;
	
	@Override
	public Long save(PartnerBean bean) {
		Long partnerid = this.partnerDao.insert(bean);
		if(bean.getManagerVo() != null){
			ManagerVo u = bean.getManagerVo();
			if(u.getId() == null){
				u.setPartnerid(partnerid);
				u.setParentid(ThreadLocals.getBackUser().getId());
				u.setType(bean.getType()+9);
				this.managerDao.saveUser(u);
			}else{
				this.managerDao.updateUser(u);
			}
		}
		return partnerid;
	}

	@Override
	public Integer update(PartnerBean bean) {
		Integer count = this.partnerDao.update(bean);
		if(bean.getManagerVo() != null){
			ManagerVo u = bean.getManagerVo();
			if(u.getId() == null){
				u.setPartnerid(bean.getId());
				u.setParentid(ThreadLocals.getBackUser().getId());
				this.managerDao.saveUser(u);
			}else{
				this.managerDao.updateUser(u);
			}
		}
		return count;
	}
	

	@Override
	public Integer dels(String ids) {
		return this.partnerDao.dels(ids);
	}

	@Override
	public List<PartnerBean> queryList(PartnerBean par, Page page) {
		return this.partnerDao.queryList(par, page);
	}

	@Override
	public List<CityBean> queryCityList(CityBean city) {
		return this.partnerDao.query(city, CityBean.class, null);
	}

	@Override
	public List<PartnerBean> queryTree() {
		return this.partnerDao.queryTree();
	}

	@Override
	public PartnerBean queryById(Long partnerid) {
		PartnerBean par = new PartnerBean();
		par.setId(partnerid);
		List<PartnerBean> list = this.partnerDao.queryList(par, null);
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		PartnerBean retBean = list.get(0);
		ManagerVo vo = new ManagerVo();
		vo.setPartnerid(partnerid);
		List<ManagerVo> userList = this.managerDao.getUserList(vo, null);
		if(CollectionUtils.isNotEmpty(userList)){
			retBean.setManagerVo(userList.get(0));
		}
		return retBean;
	}

}
